import { VuexModule, Module, MutationAction, Mutation, Action, getModule } from 'vuex-module-decorators';
import { login, logout, getInfo } from '@/api/login';
import { getToken, setToken, removeToken, setUserId, getUserId, removeUserId } from '@/utils/auth';
import store from '@/store';

export interface IUserState {
  id: number;
  name: string;
  userinfo: object;
  roles: string[];
}

@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
  public id = 0;
  public name = '';
  public userinfo = {};
  public roles = [];

  @Action({ commit: 'SET_TOKEN' })
  public async Login(userInfo: { name: string, password: string}) {
    const username = userInfo.name.trim();
    const { data } = await login(username, userInfo.password);
    setUserId(data.id);
    console.log(data)
    return data.id;
  }

  @Action({ commit: 'SET_TOKEN' })
  public async FedLogOut() {
    removeUserId();
    return '';
  }

  @MutationAction({ mutate: [ 'roles', 'name', 'userinfo' ] })
  public async GetInfo() {
    const id = getUserId();
    if (id === undefined) {
      throw Error('GetInfo: token is undefined!');
    }
    const { data } = await getInfo(id);
    if (data.name) {
      return {
        roles: data.roles,
        name: data.name,
        userinfo: data,
      };
    } else {
      throw Error('GetInfo: roles must be a non-null array!');
    }
  }

  @MutationAction({ mutate: [ 'id', 'roles' ] })
  public async LogOut() {
    // if (getToken() === undefined) {
    //   throw Error('LogOut: token is undefined!');
    // }
    // await logout();
    // removeToken();
    removeUserId();
    return {
      id: null,
      roles: [],
    };
  }

  @Mutation
  private SET_TOKEN(id: number) {
    this.id = id;
  }
}

export const UserModule = getModule(User);
